/*
 * Copyright (c) 2021-2031, 河北计全科技有限公司 (https://www.jeequan.com & jeequan@126.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sword.invoice.spring;

import com.sword.common.strategy.ISCommonStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @description: Spring 框架下, 获取Beans静态函数方法。
 * @Author terrfly
 * @Date 2019/12/31 13:57
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

        private static ApplicationContext applicationContext = null;

        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            if(SpringContextUtil.applicationContext == null){
                SpringContextUtil.applicationContext  = applicationContext;
            }
        }

        /** 获取applicationContext */
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }



        public static <T extends ISCommonStrategy> T create(String channel, Class<T> clazz) {
            var beansOfType = getApplicationContext().getBeansOfType(clazz);
            return beansOfType.values().stream()
                    .filter(strategy -> strategy.getChannelCode().equals(channel))
                    .findFirst()
                    .orElseThrow(() -> new RuntimeException("不支持的能力"));
        }


    }
